package monash.med.crystallography.DataSetTools.DiffdumpXML;

import java.io.ByteArrayOutputStream;
import java.io.File;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

import trdDatafile.jaxb.Datafile;
import trdDatafile.jaxb.ObjectFactory;
import trdDatafile.jaxb.Datafile.OscillationRange;

import com.sun.xml.bind.marshaller.NamespacePrefixMapper;

/**
 * 
 * @author steve
 */
public class DiffdumpXML extends NamespacePrefixMapper
{

	private JAXBContext jaxbContext;
	private ObjectFactory objFactory;
	Marshaller marshaller;
	private Datafile datafile;

	public DiffdumpXML()
	{
		try
		{
			jaxbContext = JAXBContext.newInstance("trdDatafile.jaxb");
		} catch (JAXBException j)
		{
			j.printStackTrace();
		}
		objFactory = new ObjectFactory();

		datafile = objFactory.createDatafile();

	}

	public String extractMetadata(File image)
	{
		try
		{
			

			//DiffractionImage dd = new DiffractionImage(image.getAbsolutePath());
            DiffdumpOut dd = new DiffdumpOut(image.getAbsolutePath());
            System.out.println("Extracting data from image: " + image);

			try
			{

				datafile.setImageType(dd.getImageType());

				OscillationRange o = objFactory.createDatafileOscillationRange();
				o.setStart((float) dd.getOscillationStart());
				o.setEnd((float) dd.getOscillationEnd());
				datafile.getOscillationRange().add(o);

				datafile.setExposureTime((float) dd.getExposureTime());
				datafile.setDetectorSN(dd.getDetectorsn());
				datafile.setXrayWavelength((float) dd.getWavelength());
				datafile.setDirectBeamXPos((float) dd.getBeamCenterX());
				datafile.setDirectBeamYPos((float) dd.getBeamCenterY());
				datafile.setDetectorDistance((float) dd.getDistanceToDetector());
				datafile.setImageSizeX((float) dd.getImageSizeX());
				datafile.setImageSizeY((float) dd.getImageSizeY());
				datafile.setPixelSizeX((float) dd.getPixelSizeX());
				datafile.setPixelSizeY((float) dd.getPixelSizeY());
				datafile.setTwoTheta((float) dd.getTwoThetaValue());

				ByteArrayOutputStream out = new ByteArrayOutputStream();

				marshaller = jaxbContext.createMarshaller();
				marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, new Boolean(true));
				marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
				marshaller.setProperty("com.sun.xml.bind.namespacePrefixMapper", this);
				marshaller.marshal(datafile, out);
				String output = out.toString(); // TODO: Find out what this returns if
				out.close();

				return output;
				// error

			} catch (JAXBException j)
			{
				j.printStackTrace();
			}

			return "Error";

		} catch (Exception e)
		{
			e.printStackTrace();
			
			return "Error";
			
		}
	}

	@Override
	public String getPreferredPrefix(String namespaceUri, String suggestion, boolean requirePrefix)
	{
		return "trd";
	}

}